package cn.gem.rainbow.cfg.web.filter;

import cn.gem.rainbow.cfg.SystemParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import java.util.ArrayList;
import java.util.List;

@Configuration
@Component
@EnableAutoConfiguration
public class WebFilterConfig {

    @Autowired
    private  SystemParam systemParam;


    @Bean
    public Filter limitFilter() {
        return new LimitFilter();
    }


    @Bean
    public Filter timeFilter(){
        return new ReqTimeFilter();
    }
    @Bean
    public Filter doubleReqFilter(){
        return new DoubleReqFilter();
    }


    @Bean
    public FilterRegistrationBean limitFilterRegister(){
        FilterRegistrationBean limitRegistrationBean = new FilterRegistrationBean();
        limitRegistrationBean.setFilter(limitFilter());

        String url = systemParam.getLimitUrl();
        if (!StringUtils.isEmpty(url)) {
            String[] param = url.split(",");
            limitRegistrationBean.addUrlPatterns(param);
        }
        limitRegistrationBean.setName("limitFilter");
        limitRegistrationBean.setOrder(1);

        return limitRegistrationBean;
    }






    /**
     * 相比使用@Component注解，这种方式配置 过滤器 有个优点，即可以自由配置优先级/配置的url
     *
     * 需要注意的是 优先级执行顺序
     *
     * 假设只有2个filer A\B 且ORDER排序为 1、2
     *
     * 则实际执行顺序为
     *  过滤A请求参数-->过滤B请求参数-->过滤B响应结果-->过滤A响应结果
     *     即 1进，2进，2出，1出
     *
     * @return FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean customReqTimeFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean() ;
        filterRegistrationBean.setFilter(timeFilter());
        List<String> urls = new ArrayList<>();
        // 匹配所有请求路径
        urls.add("/*");
        filterRegistrationBean.setUrlPatterns(urls);
        filterRegistrationBean.addInitParameter("pKey", "pValue");
        filterRegistrationBean.setName("customReqTimeFilter");
        //设置优先级
        filterRegistrationBean.setOrder(2);
        return filterRegistrationBean;
    }



    @Bean
    public FilterRegistrationBean customFilter2(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean() ;
        filterRegistrationBean.setFilter(doubleReqFilter());
        List<String> urls = new ArrayList<>();
        // 匹配所有请求路径
        urls.add("/*");
        filterRegistrationBean.setUrlPatterns(urls);
        filterRegistrationBean.addInitParameter("pKey2", "pValue2");
        filterRegistrationBean.setName("doubleReqFilter");
        filterRegistrationBean.setOrder(3);
        return filterRegistrationBean;
    }
}
